﻿namespace npantarhei.visualdesigner.CustomCode.CodeGeneration
{
	using System;
	using System.IO;
	using System.Text;
	using EnvDTE;
	using Microsoft.VisualStudio.TextTemplating.VSHost;

	[System.Runtime.InteropServices.Guid("27BF8542-FF03-4F08-AB7A-D2DDBD6F4B49")]
	public class CodeGenerator : TemplatedCodeGenerator
	{
		protected override byte[] GenerateCode(string inputFileName, string inputFileContent)
		{
			// Replace the supplied file contents with the template we want to run     
			inputFileContent = Encoding.UTF8.GetString(CodeGenerationResource.FlowGeneratorTemplate);

			// Substitute the name of the current model file into the template.    
			var fi = new FileInfo(inputFileName);    
			inputFileContent = inputFileContent.Replace("Sample.flowmodel", fi.Name);    
			
			// Now just delegate the rest of the work to the base class    
			var data = base.GenerateCode(inputFileName, inputFileContent);    
			var ascii = new byte[data.Length - 3];    
			Array.Copy(data, 3, ascii, 0, data.Length - 3);    
			
			return ascii;   
		}

		protected override string ProcessTemplate(string inputFileName, string inputFileContent, ITextTemplating processor, Microsoft.VisualStudio.Shell.Interop.IVsHierarchy hierarchy)
		{
			this.UpdateBuildAction(inputFileName);

			return base.ProcessTemplate(inputFileName, inputFileContent, processor, hierarchy);
		}

		private void UpdateBuildAction(string inputFileName)
		{
			var projectItem = Dte.Solution.FindProjectItem(inputFileName);
			if (projectItem == null) return;

			var targetFileName = projectItem.Properties.Item("CustomToolOutput").Value.ToString();
			if (string.IsNullOrWhiteSpace(targetFileName)) return;

			var targetFileItem = Dte.Solution.FindProjectItem(targetFileName) as ProjectItem;
			if (targetFileItem == null) return;

			if (targetFileItem.Properties.Item("ItemType").Value.ToString() != "Embedded Resource")
			{
				targetFileItem.Properties.Item("ItemType").Value = "Embedded Resource";
				targetFileItem.Properties.Item("BuildAction").Value = 3;
			}
		}
	}
}
